define(['app', 'js/directive/listTree', 'js/filter/tree2Arr', 'datetime', 'pagination', 'autocomplete', 'filesaver', 'editor', 'fileupload'], function(app) {
    'use strict';
    /*manage knowledgeproperty*/
    app.controller('Knowledgeright', function($scope, dataFactoryCRM, $rootScope, $q, $compile, Upload, $http, $timeout) {
        $scope.knowledgeId = '';
        $rootScope.UserId;
        $scope.disableInput = false;
        $scope.editdisableInput;
        $scope.sectorstree;
        $scope.sectorRes;
        $scope.allcompany;
        $scope.is_hide = 1;
        $scope.hide_setting = 1;
        $scope.knowledgenode_id;
        $scope.knowledgespotname;
        $scope.is_allcompany = 0;
        $scope.is_showlevelmanager;
        $scope.is_editshowlevelmanager;
        $scope.code;
        $scope.getedituserid;
        $scope.initializing = true;
        $scope.param = {};
        $scope.param.display;
        $scope.KnowledgeSource = {};
        $scope.editparam = {};
        $scope.userparam = { AddUserOnlyReadRights: [], AddUserWriteRights: [], righttype: '', knowledge_id: '' };
        $scope.edituserparam = { EditUserOnlyReadRights: [], EditUserWriteRights: [], readonly: [], write: [], righttype: '', knowledge_id: '' };
        $scope.editsectorparam = { EditSectorOnlyReadRights: [], EditSectorWriteRights: [], sectorreadonly: [], sectorwrite: [], righttype: '', knowledge_id: '' };
        $scope.readonlyusername = [];
        $scope.writeusername = [];
        // knolwedgeright list
        $scope.KnowledgeRightList = function() {
            dataFactoryCRM.getDataByAPI('Knowledgeright/Index').then(function(d) {
                if (d.rcode) {
                    $scope.KnowledgeSource = d.data;
                    $scope.KnowledgeNodeTree(d.data);
                }
            });
        }
        $scope.KnowledgeRightList();

        //get Login User Id
        $scope.getuserid = function() {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('Knowledgeright/LoginUserId').then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        //get Username 
        $scope.getusername = function() {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('Knowledgeright/GetUserName').then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // watch one level manage
        $scope.$watch('param.addknowledgecode', function(nv, ov) {
            if ($('#addnodecode').val().length > 2) {
                $scope.is_showlevelmanager = 0;
                // $scope.disableInput = true;
            } else {
                $scope.is_showlevelmanager = 1;
                // $scope.disableInput = false;
            }
        })


        // watch one level manage
        $scope.$watch('editparam.editknowledgecode', function(nv, ov) {
            if ($scope.initializing) {
                $scope.initializing = false;
            } else {
                if ($scope.editparam.editknowledgecode.length > 2) {
                    $scope.editparam.is_show = 0;
                } else {
                    $scope.editparam.is_show = 1;
                }
            }

        })

        // 
        // add knowledge_spot
        $scope.AddKnowledgeRight = function() {
            function init() {
                $('#knowledge_spot_add').form('clear');
                $('#addknowledgeadmin').val('');
                $('#addknowledgeadminId_value').val('');
                $('#edituserid').val('');
                $rootScope.UserId = '';
                $scope.param.GetUserID = '';
            }
            init();
            $scope.getuserid().then(function(d) {
                if (d.data == 1) {
                    $scope.param.display = true;
                }
            });
            $scope.getusername().then(function(d) {
                $scope.addknowledgeadminData = d.data;
            });
            $('.ui.add.modal').modal({
                observeChanges: true,
                onApprove: function() {
                    if ($('#knowledge_spot_add').form('is valid')) {
                        function addSuccess() {
                            setTimeout(function() {
                                $('.modal1').modal('show');
                                //3s后关闭
                                setTimeout(function() {
                                    $('.modal1').modal('hide')
                                }, 3000)
                            }, 1000);
                        }
                        /**添加失败 */
                        function addFail() {
                            //添加失败了,
                            setTimeout(function() {
                                $('.modal2').modal('show');
                                //3s后关闭
                                setTimeout(function() {
                                    $('.modal2').modal('hide')
                                }, 3000)
                            }, 1000);
                        }
                        dataFactoryCRM.postDataByAPI('Knowledgeright/AddKnowledgeSpot', $scope.param).then(function(d) {
                            if (d) {
                                addSuccess();
                                $scope.KnowledgeRightList();
                            } else {
                                addFail();
                            }

                        });
                        return true;
                    } else {
                        return false;
                    }
                }
            }).modal('show');
        }

        //add  knowledgespotadmin augocomplete 
        $scope.addknowledgeadminselect = function(selected) {
            if (selected) {
                var UserId = selected.originalObject.user_id;
                $('#addknowledgeadmin').val(UserId);
                $scope.param.GetUserID = UserId;
                $rootScope.UserId = UserId;
            }
        }

        //edit  knowledgespotadmin augocomplete 
        $scope.editknowledgeadminselect = function(selected) {
            if (selected) {
                var UserId = selected.originalObject.user_id;
                $('#editknowledgeadmin').val(UserId);
                $scope.editparam.GetUserID = UserId;
                $rootScope.UserId = UserId;
            }
        }

        // add angucomplete validate
        $scope.addknowledgeadmininputChanged = function($item) {
            $scope.detect = $item;
            $scope.$watch('UserId', function(newvalue, oldvalue) {
                if (newvalue != oldvalue) {
                    dataFactoryCRM.postDataByAPI('Knowledgeright/getnickname', { user_id: $rootScope.UserId })
                        .then(function(d) {
                            if (d.rcode) {
                                $scope.usernickname = d.data;
                            }
                        });
                }
            });
            $scope.$watch('detect', function(newvalue, oldvalue) {
                if ($rootScope.UserId && $scope.detect != $scope.usernickname) {
                    $('#addknowledgeadmin').val('');
                } else if ($scope.detect == $scope.usernickname) {
                    $('#addknowledgeadmin').val($rootScope.UserId);
                }
            });
        }


        //edit angucomplete validate
        $scope.editknowledgeadmininputChanged = function($item) {
            $scope.detect = $item;
            $scope.$watch('UserId', function(newvalue, oldvalue) {
                dataFactoryCRM.postDataByAPI('Knowledgeright/getnickname', { user_id: $rootScope.UserId })
                    .then(function(d) {
                        if (d.rcode) {
                            $scope.usernickname = d.data;
                        }
                    });
            });
            $scope.$watch('detect', function(newvalue, oldvalue) {
                if ($rootScope.UserId && $scope.detect != $scope.usernickname) {
                    $('#editknowledgeadmin').val('');
                } else if ($scope.detect == $scope.usernickname) {
                    $('#editknowledgeadmin').val($rootScope.UserId);
                }
            });
        }

        // edit knowledgeSpot 
        $scope.EditKnowledgeRight = function() {
            $('#editknowledgeadminId').attr("disable-input", false);
            $('#editknowledgeadminId_value').removeAttr("disabled");
            $scope.is_editshowlevelmanager;
            $scope.editparam.is_show = 0;
            $rootScope.UserId = '';
            var key = $scope.knowledgeId;
            $scope.getedituserid = $scope.knowledgeId;
            $scope.editparam.knowledgespotid = key;
            $scope.getuserid().then(function(d) {
                if (d.data == 1) {
                    $scope.editparam.display = true;
                }
            });
            $scope.getusername().then(function(d) {
                $scope.editknowledgeadminData = d.data;
            });

            $scope.geteditdata(key).then(function(d) {
                $scope.editparam.is_show = d.is_show;
                $scope.editparam.editknowledgespot = d.data.name;
                $scope.editparam.editknowledgecode = d.data.code;
                // 
                $scope.editparam.editadminright = d.data.level_one_manager;
                // 
                $('#editknowledgeadminId_value').val(d.data.nickname);
                $('#editknowledgeadmin').val(d.data.level_one_manager);
                $rootScope.UserId = d.data.level_one_manager;
            });
            $('.ui.edit.modal').modal({
                observeChanges: true,
                onApprove: function() {
                    if ($('#knowledge_spot_edit').form('is valid')) {
                        dataFactoryCRM.postDataByAPI('Knowledgeright/EditKnowledgeSpot', $scope.editparam).then(function(d) {
                            if (d) {
                                $(".ui.small.modal.editOk").modal('show');
                                setTimeout(function() {
                                    $('.ui.small.modal.editOk').modal('hide')
                                }, 3000);
                                $scope.KnowledgeRightList();
                                $scope.condition($scope.knowledgeId, '', '');
                            } else {
                                $(".ui.modal.editFail").modal('show');
                                setTimeout(function() {
                                    $('.ui.modal.editFail').modal('hide')
                                }, 3000);
                            }
                        });
                        return true;
                    } else {
                        return false;
                    }

                }
            }).modal('show');
        }

        // get the data of knolwedge_spot_id in function editknowledge
        $scope.geteditdata = function(_d) {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('Knowledgeright/EditKnowledgeSpot?id=' + _d).then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // checkbox click
        $scope.checkboxclick = function() {
            if ($scope.allcompany) {
                $scope.is_allcompany = 1;
            } else {
                $scope.is_allcompany = 0;
            }
        }

        $scope.checkboxclick();

        // knowledge_node  setting in sector right
        $scope.SectorParam = function(_d) {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('Knowledgeright/SectorParam?id=' + _d).then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // knowledge_node setting in user right
        $scope.UserParamRight = function(_d) {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('Knowledgeright/UserParamRight?id=' + _d).then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // get the knowledge node name
        $scope.getnodename = function(_d) {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('Knowledgeright/GetNodeName?id=' + _d).then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        //modify knowledgespot in user right
        $scope.ModifyUserRight = function() {
            $('#knowledge_spot_user_edit').form('clear');
            $scope.edituserright = {};
            $scope.edituserparam.sector = false;
            var knowledgeTrans = $scope.knowledgeId;
            $scope.edituserparam.knowledgespotid = knowledgeTrans;
            dataFactoryCRM.getDataByAPI('Knowledgeright/EditSettingKnowledgeSpot?knowledge_spot_id=' + $scope.knowledgeId).then(function(d) {
                if (d.data.EditUserOnlyReadRights && d.data.EditUserWriteRights) {
                    $scope.edituserparam = d.data;
                } else {
                    // why array init ,but there is to be define over time
                    if (!d.data.EditUserOnlyReadRights && !d.data.EditUserWriteRights) {
                        $scope.edituserparam = { EditUserOnlyReadRights: [], EditUserWriteRights: [], readonly: [], write: [] };
                    } else {
                        if (d.data.EditUserOnlyReadRights) {
                            $scope.edituserparam = { EditUserWriteRights: [], write: [] };
                            $scope.edituserparam.EditUserOnlyReadRights = d.data.EditUserOnlyReadRights;
                            $scope.edituserparam.readonly = d.data.readonly;
                        }
                        if (d.data.EditUserWriteRights) {
                            $scope.edituserparam = { EditUserOnlyReadRights: [], readonly: [] }; //mistake array corvered
                            $scope.edituserparam.EditUserWriteRights = d.data.EditUserWriteRights;
                            $scope.edituserparam.write = d.data.write;
                        }
                    }

                }
            });
            $('.ui.edituser.modal').modal({
                observeChanges: true,
                onApprove: function() {
                    $("input[name='edit[readonlyright][]']").each(function() {
                        if ($(this).prop('checked')) {
                            var edituser = $scope.edituserparam.EditUserOnlyReadRights.indexOf(parseInt($(this).val()));
                            if (edituser === -1) {
                                $scope.edituserparam.EditUserOnlyReadRights.push(parseInt($(this).val()));
                            }
                        }

                    });
                    $("input[name='edit[writeright][]']").each(function() {
                        if ($(this).prop('checked')) {
                            var editwrite = $scope.edituserparam.EditUserWriteRights.indexOf(parseInt($(this).val()));
                            if (editwrite === -1) {
                                $scope.edituserparam.EditUserWriteRights.push(parseInt($(this).val()));
                            }
                        }
                    });
                    dataFactoryCRM.postDataByAPI('Knowledgeright/EditSettingKnowledgeSpot', { param: $scope.edituserparam, knowledge: $scope.knowledgeId }).then(function(d) {
                        $scope.KnowledgeRightList();

                    });
                    return true;
                }
            }).modal('show');
        }

        // get subcompany 
        $scope.subcompany = function() {
            dataFactoryCRM.getDataByAPI('Knowledgeright/getsubcompany').then(function(d) {
                if (d.rcode) {
                    $scope.editcallsubcompany = d.data;
                } else {
                    $scope.editcallsubcompany = [];
                }
            });
        }

        $scope.subcompany();

        // //get sector of the subcompany
        // $scope.getsector = function(_d) {
        //     var deferred = $q.defer();
        //     dataFactoryCRM.getDataByAPI('Knowledgeright/GetSector?subcompany_id=' + _d).then(function(d) {
        //         if (d.rcode == 1) {
        //             deferred.resolve(d);
        //         } else {
        //             deferred.reject('call function error');
        //         }
        //     });
        //     return deferred.promise;
        // }


        // // connected function subcompany with sector user
        // $scope.$watch('edituserparam.subcompany', function(newvalue, oldvalue) {
        //     if (newvalue != oldvalue) {
        //         if ($scope.edituserparam.subcompany) {
        //             $scope.getsector($scope.edituserparam.subcompany).then(function(d) {
        //                 if (d.rcode == 1) {
        //                     $scope.EditSectorSource = d.data;
        //                 }
        //             });
        //         }
        //     }
        // });

        //get user of the sector
        $scope.getuser = function(_d) {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('Knowledgeright/GesUser?sector_id=' + _d).then(function(d) {
                deferred.resolve(d);
            });
            return deferred.promise;
        }

        // connected function sector with user edit
        $scope.$watch('edituserparam.subcompany', function(newvalue, oldvalue) {
            if (newvalue != oldvalue) {
                $("input[name='edit[readonlyright][]']").each(function() { $(this).prop('checked', false); });
                $("input[name='edit[writeright][]']").each(function() { $(this).prop('checked', false); });
                $scope.getuser($scope.edituserparam.subcompany).then(function(d) {
                    if (d.rcode) {
                        $scope.edituserright = d.data;
                        // need judge of time out
                        setTimeout(function() {
                            $scope.usercheckboxchecked();
                        }, 100);
                    } else {
                        $scope.edituserright = {};
                    }
                });
            }
        });

        // checkbox checked
        $scope.usercheckboxchecked = function() {
            var vchk = 0;
            var wchk = 0;
            var readonly = $scope.edituserparam.EditUserOnlyReadRights;
            var write = $scope.edituserparam.EditUserWriteRights;
            if (readonly) {
                $("input[name='edit[readonlyright][]']").each(function() {
                    vchk = parseInt($(this).val());
                    if (readonly.indexOf(vchk) >= 0) {
                        $(this).prop('checked', true);
                    }
                });
            } else {
                $("input[name='edit[readonlyright][]']").each(function() {
                    $(this).prop('checked', false);
                });
            }

            if (write) {
                $("input[name='edit[writeright][]").each(function() {
                    wchk = parseInt($(this).val());
                    if (write.indexOf(wchk) >= 0) {
                        $(this).prop('checked', true);
                    }
                });
            } else {
                $("input[name='edit[writeright][]").each(function() {
                    $(this).prop('checked', false);
                });
            }

        }

        // checkbox only-right edit
        $scope.EditOnlyReadRight = function(index) {
            var editonlyread = $scope.edituserright[index];
            var editverifyreadonly = $scope.edituserparam.EditUserOnlyReadRights.indexOf(parseInt(editonlyread.user_id));
            if (editverifyreadonly === -1) {
                $scope.edituserparam.EditUserOnlyReadRights.push(parseInt(editonlyread.user_id));
                $scope.edituserparam.readonly.push(editonlyread.nickname);
            } else {
                $scope.edituserparam.EditUserOnlyReadRights.splice(editverifyreadonly, 1);
                $scope.edituserparam.readonly.splice(editverifyreadonly, 1);
            }
            $scope.edituserparam.righttypereadonly = 1;
        }

        // checkbox write right edit
        $scope.EditWriteRight = function(index) {
            var editwrite = $scope.edituserright[index];
            var editverifywrite = $scope.edituserparam.EditUserWriteRights.indexOf(parseInt(editwrite.user_id));
            if (editverifywrite === -1) {
                $scope.edituserparam.EditUserWriteRights.push(parseInt(editwrite.user_id));
                $scope.edituserparam.write.push(editwrite.nickname);
            } else {
                $scope.edituserparam.EditUserWriteRights.splice(editverifywrite, 1);
                $scope.edituserparam.write.splice(editverifywrite, 1);
            }
            $scope.edituserparam.righttypewrite = 2;
        }


        // get sectortree
        $scope.SectorTree = function() {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('Knowledgeright/GetSectorTree').then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // sector checkbox checked
        $scope.sectorcheckboxchecked = function() {
            var vchk = 0;
            var wchk = 0;
            var readonly = $scope.editsectorparam.EditSectorOnlyReadRights;
            var write = $scope.editsectorparam.EditSectorWriteRights;
            if (readonly) {
                $("input[name='edit[readonlysector][]']").each(function() {
                    vchk = parseInt($(this).val());
                    if (readonly.indexOf(vchk) >= 0) {
                        $(this).prop('checked', true);
                    }
                });
            } else {
                $("input[name='edit[readonlysector][]']").each(function() {
                    $(this).prop('checked', false);
                });
            }
            if (write) {
                $("input[name='edit[writersector][]").each(function() {
                    wchk = parseInt($(this).val());
                    if (write.indexOf(wchk) >= 0) {
                        $(this).prop('checked', true);
                    }
                });
            } else {
                $("input[name='edit[writersector][]").each(function() {
                    $(this).prop('checked', false);
                });
            }
        }

        // modify knowledgespot in sector right
        $scope.ModifySectorRight = function() {
            var knowledgeTransSector = $scope.knowledgeId;
            $scope.SectorTree().then(function(d) {
                var treeArr = d.sector;
                $scope.sectorstree = d.data;
                $scope.sectorRes = d.sector;

                function createTree(treeArr) {
                    var treeStr = '<div class="ui accordion">'
                    for (var i = 0; i < treeArr.length; i++) {
                        if (i == 0) {
                            treeStr += '<div class="active title" onselectstart="return false"><i class="dropdown icon"></i>' + treeArr[i].sector_name + '<div class="ui checkbox fr"><input type="checkbox" name="edit[writersector][]" value="' + treeArr[i]['sector_id'] + '" ng-click="EditWriteSector(' + i + ')"><label></label></div><div class="ui checkbox fr"><input type="checkbox" name="edit[readonlysector][]" value="' + treeArr[i]['sector_id'] + '" ng-click="EditOnlyReadSector(' + i + ')"><label></label></div>' + '</div>';
                        } else if (treeArr[i].parent_sector > treeArr[i - 1].parent_sector) {
                            treeStr += '<div class="active content"><div class="accordion"><div class="active title" onselectstart="return false"><i class="dropdown icon"></i>' + treeArr[i].sector_name + '<div class="ui checkbox fr"><input type="checkbox" name="edit[writersector][]" value="' + treeArr[i]['sector_id'] + '" ng-click="EditWriteSector(' + i + ')"><label></label></div><div class="ui checkbox fr"><input type="checkbox" name="edit[readonlysector][]" value="' + treeArr[i]['sector_id'] + '" ng-click="EditOnlyReadSector(' + i + ')"><label></label></div>' + '</div>';
                        } else if (treeArr[i].parent_sector == treeArr[i - 1].parent_sector) {
                            treeStr += '<div class="active content"></div><div class="active title" onselectstart="return false"><i class="dropdown icon"></i>' + treeArr[i].sector_name + '<div class="ui checkbox fr"><input type="checkbox" name="edit[writersector][]" value="' + treeArr[i]['sector_id'] + '" ng-click="EditWriteSector(' + i + ')"><label></label></div><div class="ui checkbox fr"><input type="checkbox" name="edit[readonlysector][]" value="' + treeArr[i]['sector_id'] + '" ng-click="EditOnlyReadSector(' + i + ')"><label></label></div>' + '</div>';
                        } else if (treeArr[i].parent_sector < treeArr[i - 1].parent_sector) {

                            treeStr += '<div class="active content"></div>';
                            var num = (treeArr[i - 1].parent_sector - treeArr[i].parent_sector);
                            for (var j = 0; j < num; j++) {
                                treeStr += '</div></div>';
                            }
                            treeStr += '<div class="active title" onselectstart="return false"><i class="dropdown icon"></i>' + treeArr[i].sector_name + '<div class="ui checkbox fr"><input type="checkbox" name="edit[writersector][]" value="' + treeArr[i]['sector_id'] + '" ng-click="EditWriteSector(' + i + ')"><label></label></div><div class="ui checkbox fr"><input type="checkbox" name="edit[readonlysector][]" value="' + treeArr[i]['sector_id'] + '" ng-click="EditOnlyReadSector(' + i + ')"><label></label></div>' + '</div>';
                        }
                        if (i == treeArr.length - 1) {
                            treeStr += '<div class="active content"></div>';
                        }
                    }
                    var $html = $compile(treeStr)($scope);
                    $('#knowledge_spot_sector_edit').html($html);
                    $('#knowledge_spot_sector_edit .ui.accordion').accordion({
                        exclusive: false,
                        selector: {
                            trigger: '.title .icon'
                        }
                    });
                    $('#knowledge_spot_sector_edit .ui.accordion').find('.accordion').css("marginLeft", "20px");
                }
                createTree(treeArr);
            });

            // 
            setTimeout(function() {
                dataFactoryCRM.getDataByAPI('Knowledgeright/SectorManage?knowledge_spot_id=' + $scope.knowledgeId).then(function(d) {
                    if (d.data.EditSectorOnlyReadRights && d.data.EditSectorWriteRights) {
                        $scope.editsectorparam = d.data;
                    } else {
                        // why array init ,but there is to be define over time
                        if (!d.data.EditSectorOnlyReadRights && !d.data.EditSectorWriteRights) {
                            $scope.editsectorparam = { EditSectorOnlyReadRights: [], EditSectorWriteRights: [], sectorreadonly: [], sectorwrite: [] };
                        } else {
                            if (d.data.EditSectorOnlyReadRights) {
                                $scope.editsectorparam = { EditSectorWriteRights: [], sectorwrite: [] };
                                $scope.editsectorparam.EditSectorOnlyReadRights = d.data.EditSectorOnlyReadRights;
                                $scope.editsectorparam.sectorreadonly = d.data.sectorreadonly; //lack of this code .so there is a bug
                            }
                            if (d.data.EditSectorWriteRights) {
                                $scope.editsectorparam = { EditSectorOnlyReadRights: [], sectorreadonly: [] }; //mistake array corvered
                                $scope.editsectorparam.EditSectorWriteRights = d.data.EditSectorWriteRights;
                                $scope.editsectorparam.sectorwrite = d.data.sectorwrite;
                            }
                        }

                    }
                });
                setTimeout(function() {
                    $scope.sectorcheckboxchecked();
                }, 100);
            }, 100);
            $('.ui.sector.modal').modal({
                allowMultiple: true,
                observeChanges: true,
                onApprove: function() {
                    $("input[name='edit[readonlysector][]']").each(function() {
                        if ($(this).prop('checked')) {
                            var editsector = $scope.editsectorparam.EditSectorOnlyReadRights.indexOf(parseInt($(this).val()));
                            if (editsector === -1) {
                                $scope.editsectorparam.EditSectorOnlyReadRights.push(parseInt($(this).val()));
                            }
                        }

                    });
                    $("input[name='edit[writersector][]']").each(function() {
                        if ($(this).prop('checked')) {
                            var editsector = $scope.editsectorparam.EditSectorWriteRights.indexOf(parseInt($(this).val()));
                            if (editsector === -1) {
                                $scope.editsectorparam.EditSectorWriteRights.push(parseInt($(this).val()));
                            }
                        }
                    });
                    dataFactoryCRM.postDataByAPI('Knowledgeright/SectorManage', { param: $scope.editsectorparam, knowledge_id: $scope.knowledgeId }).then(function(d) {
                        $scope.KnowledgeRightList();
                    });
                    return true;
                }
            }).modal('show');
        }

        // modify sector read-only right manage
        $scope.EditOnlyReadSector = function(index) {
            var readonlysector = $scope.sectorRes[index];
            var sectorverifyreadonly = $scope.editsectorparam.EditSectorOnlyReadRights.indexOf(parseInt(readonlysector.sector_id));
            if (sectorverifyreadonly === -1) {
                $scope.editsectorparam.EditSectorOnlyReadRights.push(parseInt(readonlysector.sector_id));
                $scope.editsectorparam.sectorreadonly.push(readonlysector.sector_name);
            } else {
                $scope.editsectorparam.EditSectorOnlyReadRights.splice(sectorverifyreadonly, 1);
                $scope.editsectorparam.sectorreadonly.splice(sectorverifyreadonly, 1);
            }
            $scope.editsectorparam.righttypereadonly = 1;
        }

        // modify sector write right manage
        $scope.EditWriteSector = function(index) {
            var writesector = $scope.sectorRes[index];
            var sectorverifywrite = $scope.editsectorparam.EditSectorWriteRights.indexOf(parseInt(writesector.sector_id));
            if (sectorverifywrite === -1) {
                $scope.editsectorparam.EditSectorWriteRights.push(parseInt(writesector.sector_id));
                $scope.editsectorparam.sectorwrite.push(writesector.sector_name);
            } else {
                $scope.editsectorparam.EditSectorWriteRights.splice(sectorverifywrite, 1);
                $scope.editsectorparam.sectorwrite.splice(sectorverifywrite, 1);
            }
            $scope.editsectorparam.righttypewrite = 2;
        }

        // delete knowledge Node 
        $scope.DeleteKnowledgeNode = function() {
            if ($scope.code) {
                var code = $scope.code;
                $('.modal3').modal({
                    onApprove: function() {
                        dataFactoryCRM.postDataByAPI('Knowledgeright/DeleteKnowledgeNode', { code: code }).then(function(d) {
                            $scope.KnowledgeRightList();
                            $scope.condition('', '', '');
                        });
                        return true;
                    }
                }).modal('show');
            }

        }

        // knowledge node tree
        $scope.KnowledgeNodeTree = function(arr) {
            if (arr) {
                var treeStr = '<div class="ui accordion">'
                for (var i = 0; i < arr.length; i++) {
                    if (i == 0) {
                        treeStr += '<div class="active title" ng-click="condition(' + arr[i]['knowledge_spot_id'] + ',' + arr[i]['code'] + ',$event)"><i class="dropdown icon"></i>' + arr[i]['code'] + arr[i]['name'] + '</div>';
                    } else if (arr[i]['code'].length > arr[i - 1]['code'].length) {
                        treeStr += '<div class="active content"><div class="accordion"><div class="active title" ng-click="condition(' + arr[i]['knowledge_spot_id'] + ',' + arr[i]['code'] + ',$event)"><i class="dropdown icon"></i>' + arr[i]['code'] + arr[i]['name'] + '</div>';
                    } else if (arr[i]['code'].length == arr[i - 1]['code'].length && arr[i]['code'].length == 2) {
                        treeStr += '<div class="active content"></div><div class="active title" ng-click="condition(' + arr[i]['knowledge_spot_id'] + ',' + arr[i]['code'] + ',$event)"><i class="dropdown icon"></i>' + arr[i]['code'] + arr[i]['name'] + '</div>';
                    } else if (arr[i]['code'].length == arr[i - 1]['code'].length && arr[i]['code'].length != 2) {
                        treeStr += '<div class="active content"></div><div class="active title" ng-click="condition(' + arr[i]['knowledge_spot_id'] + ',' + arr[i]['code'] + ',$event)"><i class="dropdown icon"></i>' + arr[i]['code'] + arr[i]['name'] + '</div>';
                    } else if (arr[i]['code'].length < arr[i - 1]['code'].length) {
                        treeStr += '<div class="active content"></div>';
                        var num = (arr[i - 1]['code'].length - arr[i]['code'].length) / 2;
                        for (var j = 0; j < num; j++) {
                            treeStr += '</div></div>';
                        }
                        treeStr += '<div class="active title" ng-click="condition(' + arr[i]['knowledge_spot_id'] + ',' + arr[i]['code'] + ',$event)"><i class="dropdown icon"></i>' + arr[i]['code'] + arr[i]['name'] + '</div>';
                    }
                    if (i == arr.length - 1) {
                        treeStr += '<div class="active content"></div>';
                    }
                }
                var $html = $compile(treeStr)($scope);
                $('.treemenu').html($html);
                $(".treemenu .content").each(function() {
                    if ($(this).text() == "") {
                        $(this).prev().find(".icon").removeClass('dropdown').addClass('small minus');
                    }
                });
                $('.treemenu .ui.accordion').accordion({
                    exclusive: false,
                    selector: {
                        trigger: '.title .icon'
                    }
                });
                $('.treemenu .ui.accordion').find('.accordion').css("marginLeft", "20px");
            }
        }

        // condition selected 
        // knowledge node setting
        $scope.condition = function(k, v, $event) {
            if ($event) {
                $('.treemenu .title').removeClass('checked');
                $($event.target).addClass('checked');
            }

            $scope.edituserparam.knowledgespotid = k;
            $scope.knowledgeId = k;
            if (v.toString().length % 2 == 0) {
                $scope.code = v.toString();
            } else {
                $scope.code = '0' + v;
            }
            // console.log(v.toString().length);
            function init() {
                $scope.editsectorparam = {};
                $scope.edituserparam = {};
                $scope.knowledgespotname = '';
                $scope.hide_setting = 1;
                $scope.is_hide = 1;
            }
            init();
            $scope.SectorParam(k).then(function(d) {
                if (d.rcode) {
                    $scope.editsectorparam = d.data;
                }
            });
            $scope.UserParamRight(k).then(function(d) {
                if (d.rcode) {
                    $scope.edituserparam = d.data;
                }
            });
            $scope.getnodename(k).then(function(d) {
                if (d.rcode) {
                    $scope.knowledgespotname = d.data.name;
                    $scope.hide_setting = d.hide_setting;
                    $scope.is_hide = d.is_hide;
                }
            });
        }


    })
});